<script lang="ts" setup>
import { toF9 } from '@/utils';

import { decodeByBase64, timestampToTime } from '@vc/utils';
import pako from 'pako';
import { addCollection, removeCollection, addCompany, removeCompany, getContentApi, getFileContentApi } from '../apis';
import message from 'vc/src/common/message';
import { addMember, getGroupListAndCompanyId } from '@/components/search/apis';

const route = useRoute();
const contentRef = ref();

let params = $ref<Record<string, any>>({
  id: '', // 新闻id
  url: '', // 链接
  title: '', // 新闻标题
  date: '', // 时间戳
  source: '', // 来源
  labels: [], // 标签
  related: [], // 关联机构
  fileType: '', // 文件类型
  followed: '' // 是否收藏
});
let hasTopParams = $ref(false), // 是z否有头部信息
  isToggleExpand = $ref(false), // 展开收起
  isLoading = $ref(false), // 默认初始化加载
  bigTextOverHeight = $ref(false), // 事件类 大文本 超过最大高度 显示更多
  isOpenMore = $ref(false), // 相关企业超过10条显示更多
  isOpenMoreProcess = $ref(false); // 事件进展 超过6条 展示更多

const zlibHtml = ref<HTMLElement | null>();

isLoading = true;

// 新打开页面 进程中的新闻链接，有fileType就打开附件，没有就直接跳外链
const toNewsPage = function (item) {
  if (item.fileType) {
    window.open(`./zlibHtml.html?id=${item.newsId}&url=${item.url}`, '_blank');
  } else {
    window.open(item.url, '_blank');
  }
};
// 重置表格样式
const resetTableStyle = () => {
  if (document.querySelector('table')) {
    let contentEle = document.querySelector('#zlibHtml');
    let contentWidth = (document.querySelector('#zlibHtml') as HTMLHtmlElement).offsetWidth - (window.getComputedStyle(contentEle as any) as any).getPropertyValue('padding-left').split('px')[0];
    let tableWidth: number = document.querySelector('table')?.offsetWidth || 0;
    if (tableWidth > contentWidth) {
      (document.querySelector('table') as any).parentNode.style.width = '100%';
      (document.querySelector('table') as any).parentNode.style.whiteSpace = 'nowrap';
      (document.querySelector('table') as any).parentNode.style.overflowX = 'scroll';
    } else {
      // (document.querySelector('table') as any).style.width = '100%';
    }
  }
};
// 请求文件内容
const getFile = async function (url: string = location.href) {
  const fileUrl = decodeURIComponent((location.href.match(/\burl=([^&]*)/) || [, ''])[1] || '') || url;
  if (!fileUrl) {
    return;
  }
  const fileType = (fileUrl.split('?')[0].split('.').pop() as string).toLowerCase();

  // 编码格式
  const type = !!params.id && Number(params.id.split('_')[0]) === 5 ? 'gbk' : 'utf-8';
  console.log('编码：：：', type, fileType);

  if (fileType === 'zlib') {
    await getFileContentApi({ url: fileUrl, responseType: 'arraybuffer' })
      .then((res) => {
        isLoading = false;

        var words = new Uint8Array(res.data),
          content = new TextDecoder(type).decode(pako.inflate(words));
        content = content.replace(/<table[^>]*>/gi, '<table  cellspacing="0" max-width="100%" border="1" style="font-size:0.26rem;max-width:100%; line-height:0.4rem;">');
        content = content
          .replace(/(\\n\\r)|(\\r\\n)|(\\\\n\\\\r)|(\\\\r\\\\n)/g, '<br />')
          .replace(/(\\n)|(\\\\n)/g, '<br />')
          .replace(/(\\t)|(\\\\t)/g, '　　')
          .replace(/(FONT-SIZE|FONT-FAMILY|LINE-HEIGHT):/gi, '');

        nextTick(() => {
          (zlibHtml.value as HTMLElement).innerHTML = content;

          let _colgroup = document.getElementsByTagName('colgroup');

          for (let i = 0; i < _colgroup.length; i++) {
            (_colgroup[i].parentNode as ParentNode).removeChild(_colgroup[i]); // 删除整个colgroup
          }
          resetTableStyle();
          document.querySelectorAll('a').forEach((item) => {
            let newHref = item?.getAttribute('href')?.replaceAll('#environment_protection_new#', 'https://environment.oasis-esg.com');
            if (newHref) {
              item.setAttribute('href', newHref || '');
              item.setAttribute('target', '_blank');
            }
          });
          document.querySelectorAll('img').forEach((item) => {
            let newHref = item?.getAttribute('src')?.replaceAll('#environment_protection_new#', 'https://environment.oasis-esg.com');
            item.setAttribute('src', newHref || '');
          });
        });
      })
      .catch(() => {
        isLoading = false;

        if (params.newsUrl) {
          location.href = params.url;
        }
      });
  } else if (fileType.indexOf('htm') > -1) {
    await getFileContentApi({ url: fileUrl })
      .then((res) => {
        isLoading = false;

        var content: string = res.data;

        content = content.replace(/<br[^>]*\/>/gi, '');
        // 去掉表格行内的width
        // content = content.replace(
        //   /(<td(?:\s+\w*?\s*=\s*.+?)*)(?:\s+width=\s*.+?)((?:\s+\w*?\s*=\s*.+?)*\s*>)/g,
        //   '$1$2'
        // );
        // content = content.replace(/<td[^<>]*>\s*?<p>/gi, '<td>');
        content = content.replace(/<table[^>]*>/gi, '<table  cellspacing="0" max-width="100%" border="1" style="font-size:0.26rem;max-width:100%; line-height:0.4rem;">');

        nextTick(() => {
          (zlibHtml.value as HTMLElement).innerHTML = content;

          let _colgroup = document.getElementsByTagName('colgroup');

          for (let i = 0; i < _colgroup.length; i++) {
            (_colgroup[i].parentNode as ParentNode).removeChild(_colgroup[i]); // 删除整个colgroup
          }
          resetTableStyle();
          document.querySelectorAll('a').forEach((item) => {
            let newHref = item?.getAttribute('href')?.replaceAll('#environment_protection_new#', 'https://environment.oasis-esg.com');
            if (newHref) {
              item.setAttribute('href', newHref || '');
              item.setAttribute('target', '_blank');
            }
          });
          document.querySelectorAll('img').forEach((item) => {
            let newHref = item?.getAttribute('src')?.replaceAll('#environment_protection_new#', 'https://environment.oasis-esg.com');
            item.setAttribute('src', newHref || '');
          });
        });
      })
      .catch(() => {
        isLoading = false;

        if (params.newsUrl) {
          location.href = params.url;
        }
      });
  }
};

// 初始化加载iframe完成
const initIframe = function () {
  var ifm = document.getElementById('iframe');
  let foot = document.getElementsByClassName('related')[0];
  let footHeight = 0;
  if (foot) {
    footHeight = Math.min(160, foot.clientHeight + 8);
  }
  (ifm as any).width = document.documentElement.clientWidth;
  (ifm as any).height = document.documentElement.clientHeight - footHeight;
};

onMounted(() => {
  params = route.params;
  params.url = decodeByBase64(params.url) && decodeByBase64(params.url) !== 'null' ? decodeByBase64(params.url) : '';
  params.id = params.id ? decodeByBase64(params.id) : '';
  params.bizType = params.bizType ? decodeByBase64(params.bizType) : '';

  console.log('访问的链接:', params);
  if (params.date) {
    params.date = timestampToTime(parseInt(params.date));
  }
  if (params.labels) {
    params.labels = JSON.parse(params.labels as unknown as string);

    // app跳转带的背景色是 #+8位数，需要对前两位截取下
    params.labels.forEach((item) => {
      let color = item.color.replaceAll('#', '');
      let colorBg = item.bgColor.replaceAll('#', '');
      if (color.length > 6) {
        item.color = '#' + color.slice(2);
      }
      if (colorBg.length > 6) {
        item.bgColor = '#' + colorBg.slice(2);
      }
    });
  }
  if (params.related) {
    params.related = JSON.parse(params.related as unknown as string);
  }

  hasTopParams = Object.values({
    title: params.title,
    date: params.date,
    source: params.source,
    labels: params.labels
  }).join('')
    ? true
    : false;

  const renderData = (res) => {
    if (res.code === 200 && res.data) {
      isLoading = false;

      // 处理时间格式
      if (res?.data?.date) {
        res.data.date = timestampToTime(parseInt(res.data.date));
      }
      params = { ...params, ...res.data };

      if (res.data?.type !== 3 && res.data?.content) {
        params.url = res.data.content;
      }
      hasTopParams = Object.values({
        title: params.title,
        date: params.date,
        source: params.source,
        labels: params.labels
      }).join('')
        ? true
        : false;

      if (res.data?.type === '1' && res.data?.content) {
        // 1文件 且文件存在 直接解析文件
        getFile(params.url);
      } else if (res.data?.type === '2') {
        // 2大文本 直接展示
        nextTick(() => {
          var reg = new RegExp('\r\n', 'g');
          (zlibHtml.value as HTMLElement).innerHTML = res.data.content.replaceAll(reg, '<br/>');
        });
      } else if (res.data?.type === '3') {
        // 3外链 打开新页面
        if (params.newsUrl) {
          location.href = params.newsUrl;
        } else {
          location.href = res.data.content;
        }
      }
    }
  };

  // 优先判断 是否是新闻(id前缀5_) 且 没有附件，直接跳转外链
  let i = params.id ? params.id.split('_')[0] : '';
  if (params.id && i * 1 === 5 && !params.url && params.newsUrl) {
    location.href = params.newsUrl;
  } else if (!params.url) {
    // 链接没有传url，从接口获取
    getContentApi({
      bizType: params.bizType,
      id: params.id
    }).then((res) => {
      renderData(res);
    });
  } else {
    isLoading = true;
    if (params.id) {
      getContentApi({
        bizType: params.bizType,
        id: params.id
      }).then((res) => {
        console.log(res, 77);
        if (res.code === 200 && res) {
          getFile(params.url);
          isLoading = false;

          // 处理时间格式
          if (res?.data?.date) {
            res.data.date = timestampToTime(parseInt(res.data.date));
          }
          params = { ...params, ...res.data };
          if (res?.data?.type !== 3 && res?.data?.content) {
            params.url = res.data.content;
          }
          hasTopParams = Object.values({
            title: params.title,
            date: params.date,
            source: params.source,
            labels: params.labels
          }).join('')
            ? true
            : false;
        }
      });
    } else {
      // 直接打开附件
      getFile(params.url);
    }
  }
});

// 添加到组合
const addMemberToGroup = async (id, index) => {
  const res = await getGroupListAndCompanyId();
  if (res?.items?.length) {
    const defaultGroup = res.items.find((item) => item.isDefault === 1) || res.items[0];
    const addRes = await addMember(defaultGroup.id, [id]);
    if (addRes.code === 200) {
      params.related[index].followInfo.followed = true;
    }
  }
};
// 取消添加到组合
const monitorCancel = (item, index) => {
  removeCompany({
    groupId: item.followInfo.group.join(','),
    ids: encodeURIComponent(item.id)
  }).then((res) => {
    params.related[index].followInfo.followed = false;
  });
};

// 收藏
const collect = (id, flag) => {
  if (!flag) {
    addCollection({ newId: id }).then((res) => {
      if (res) {
        message.success({
          message: '已添加收藏',
          duration: 2000
        });
        params.followed = !params.followed;
      }
    });
  } else {
    removeCollection({ newId: id }).then((res) => {
      if (res) {
        message.success({
          message: '已取消收藏',
          duration: 2000
        });
        params.followed = !params.followed;
      }
    });
  }
};
</script>

<template>
  <div class="zlibDetailWrapper">
    <div class="html">
      <el-skeleton class="loading" title :rows="20" :loading="isLoading">
        <div class="top" v-if="hasTopParams">
          <div class="title">
            <p v-if="params.title">{{ params.title }}</p>
          </div>
          <div class="resource">
            <div
              class="tag"
              v-for="(item, index) in params.labels"
              :key="index"
              :style="{
                color: `${item.color === item.bgColor ? '#111' : item.color}`,
                background: item.bgColor
              }"
            >
              {{ item.name }}
            </div>
          </div>
          <div class="bottom_info">
            <div>
              <span v-if="params.date">{{ params.date }}</span>
              ·
              <span v-if="params.source">{{ params.source }}</span>
            </div>
            <div v-if="params.id" class="collect" :class="{ active: params.followed }" @click="collect(params.id, params.followed)">
              <span v-if="params.followed">
                <span class="icon vicon vi-pingjiaxingxing" />
                <span>已收藏</span>
              </span>
              <span v-else>
                <span class="icon vicon vi-xingxing" />
                <span>收藏</span>
              </span>
            </div>
          </div>
        </div>
        <el-skeleton :row="4" v-if="isLoading" />
        <div class="content" v-show="!isLoading">
          <!--外链-->
          <template v-if="false">
            <iframe id="iframe" frameborder="0" scrolling="auto" width="100%" :src="params.newsUrl" allowfullscreen @load="initIframe()" />
          </template>

          <template v-else>
            <!--事件链接 (进展按事件降序的，取进展最后一个)-->
            <div class="newsLink" v-if="params.process && params.process.length" @click="toNewsPage(params.process[params.process.length - 1])">
              <p class="newsLink-title">{{ params.process[params.process.length - 1].title }}</p>
              <div class="newsLink-link">
                <img src="@/assets/link.png" />
                {{ params.process[params.process.length - 1].url }}
              </div>
            </div>
            <!--正文-->
            <div
              id="zlibHtml"
              ref="zlibHtml"
              :class="{ isToggleExpand: bigTextOverHeight && !isToggleExpand }"
              :style="{
                maxHeight: bigTextOverHeight && !isToggleExpand ? '6rem' : 'unset'
              }"
            />
            <p v-if="bigTextOverHeight" class="expand" :class="{ open: !isToggleExpand }" @click="isToggleExpand = !isToggleExpand">
              {{ isToggleExpand ? '收起' : '展开' }}
            </p>
          </template>
        </div>
        <!-- 事件进展 -->
        <div class="event-process box" v-if="params.process && params.process.length > 1">
          <div class="event-title">进展 {{ params.process.length }}</div>
          <ul class="timeline">
            <li class="timeline-event" :class="{ hidden: index > 5 && !isOpenMoreProcess }" v-for="(item, index) in params.process" :key="index">
              <label v-if="index === 0" class="timeline-event-icon timeline-event-icon-first">最新</label>
              <span class="vi--shijian icon vicon" style="color: #1382ef" />
              <div class="timeline-event-process">
                <p class="timeline-event-process-time">{{ item.noticeDate }}</p>
                <div class="timeline-event-process-newsUrl" @click="toNewsPage(item)">
                  <p class="timeline-event-process-newsUrl-title">{{ item.title }}</p>
                  <p class="timeline-event-process-newsUrl-url">
                    <img src="@/assets/link.png" />
                    {{ item.url }}
                  </p>
                </div>
              </div>
            </li>
            <div v-if="params.process.length > 6" class="expand" :class="{ open: isOpenMoreProcess }" @click="isOpenMoreProcess = !isOpenMoreProcess">
              {{ isOpenMoreProcess ? '收起' : '查看更多' }}
              <i />
            </div>
          </ul>
        </div>
      </el-skeleton>
    </div>
    <div class="relateCompany" v-if="params.related && params.related.length > 0">
      <!-- 相关企业 -->
      <div class="related box">
        <div class="event-title">相关企业</div>
        <div
          class="companies"
          :style="{
            maxHeight: isOpenMore ? 'unset' : '360px',
            overflow: isOpenMore ? 'initial' : 'hidden'
          }"
        >
          <div v-for="(item, index) in params.related" :key="index" class="relatedItem">
            <div class="name" @click="toF9(item.id)">{{ item.name }}</div>
            <div class="btn" @click="addMemberToGroup(item.id, index)" v-if="item.followInfo && !item.followInfo.followed">+监控</div>
            <div class="btn monitored" v-if="item.followInfo && item.followInfo.followed">已监控</div>
          </div>
        </div>
        <div v-if="params.related.length > 10" class="expand" :class="{ open: isOpenMore }" @click="isOpenMore = !isOpenMore">
          {{ isOpenMore ? '收起' : '查看更多' }}
          <i />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
@import './index.scss';
</style>
